﻿using System;
using Microsoft.AspNetCore.Mvc;
using RedDockNet_BackEnd.Service;
using StackExchange.Redis;

namespace RedDockNet_BackEnd.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthCodeController : ControllerBase
    {
        private readonly AuthCodeService service;

        public AuthCodeController(AuthCodeService service)
        {
            this.service = service;
        }

        [HttpPost("{id:length(24)}")]
        public IActionResult Get(string id)
        {
            IActionResult result;
            RedisValue redisValue = service.GetKey(id);
            if (redisValue.HasValue)
            {
                result = this.Ok(redisValue.ToString());
            }
            else
            {
                result = this.NotFound();
            }
            return result;
        }

        [HttpPost("{id:length(24)},{authCode}")]
        public IActionResult Set(string id, string authCode)
        {
            IActionResult result;
            TimeSpan expiry = new TimeSpan(0, 5, 0);
            if (service.SetKey(id, authCode, expiry))
            {
                result = this.Ok();
            }
            else
            {
                result = this.Forbid();
            }
            return result;
        }

        [HttpPost("{id:length(24)}")]
        public IActionResult Exists(string id)
        {
            IActionResult result;
            if (service.ExistsKey(id))
            {
                result = this.Ok();
            }
            else
            {
                result = this.NotFound();
            }
            return result;
        }

        [HttpPost("{id:length(24)}")]
        public IActionResult Delete(string id)
        {
            IActionResult result;
            if (service.DeleteKey(id))
            {
                result = this.Ok();
            }
            else
            {
                result = this.NotFound();
            }
            return result;
        }
    }
}
